import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state:{
        products:[
            {name:"苹果", price:200},
            {name:"梨子", price:100},
            {name:"杨桃", price:50},
            {name:"香蕉", price:30}
        ],
        user:{
            name: window.localStorage.getItem('user' || '[]') == null ? '未登录' : JSON.parse(window.localStorage.getItem('user' || '[]')).name,
            userface: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).userface,
            username: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).username,
            roles: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).roles
        }
    },
    getters:{
        salesProducts:(state)=>{
            var salesProducts=state.products.map((product)=>{
                return {
                    name: "**" + product.name + "**",
                    price: product.price * 0.5
                }
            })
            return salesProducts        
        }
    },
    mutations:{
        reducePrice:(state, playload)=>{
            //setTimeout(() => {
                state.products.forEach(product => {
                    product.price -= playload;
                });
            //}, 3000);
        }
    },
    actions:{
        reducePriceAction:(context, playload)=>{
            setTimeout(() => {
                context.commit("reducePrice", playload);
            }, 2000);
        }
    }
});